//package com.ssy.lingxi.member.merchant.serviceimpl.web;
//
//import com.ssy.lingxi.common.constant.member.MemberTypeEnum;
//import com.ssy.lingxi.common.constant.member.RoleTypeEnum;
//import com.ssy.lingxi.common.response.PageData;
//import com.ssy.lingxi.common.response.ResponseCode;
//import com.ssy.lingxi.common.response.Wrapper;
//import com.ssy.lingxi.member.merchant.entity.RoleDO;
//import com.ssy.lingxi.member.merchant.model.bo.AuthBO;
//import com.ssy.lingxi.member.merchant.model.bo.ButtonBO;
//import com.ssy.lingxi.member.merchant.api.constant.MemberRelationTypeEnum;
//import com.ssy.lingxi.member.merchant.model.vo.basic.request.*;
//import com.ssy.lingxi.member.merchant.model.vo.basic.response.*;
//import com.ssy.lingxi.member.merchant.repository.RoleRepository;
//import com.ssy.lingxi.member.merchant.service.base.IBaseAuthService;
//import com.ssy.lingxi.member.merchant.service.base.IBaseMemberCacheService;
//import com.ssy.lingxi.member.merchant.service.feign.IPlatformTemplateFeignService;
//import com.ssy.lingxi.member.merchant.service.web.IPlatformRoleManageService;
//import com.ssy.lingxi.member.merchant.utils.AuthBOUtils;
//import org.springframework.data.domain.Page;
//import org.springframework.data.domain.PageRequest;
//import org.springframework.data.domain.Pageable;
//import org.springframework.data.domain.Sort;
//import org.springframework.data.jpa.domain.Specification;
//import org.springframework.http.HttpHeaders;
//import org.springframework.stereotype.Service;
//import org.springframework.util.CollectionUtils;
//import org.springframework.util.StringUtils;
//
//import javax.annotation.Resource;
//import javax.persistence.criteria.Predicate;
//import java.util.ArrayList;
//import java.util.List;
//import java.util.stream.Collectors;
//
///**
// * 平台后台 - 角色权限管理服务接口实现类
// * @author 万宁
// * @version 2.0.0
// * @date 2020-10-23
// */
//@Service
//public class PlatformRoleManageServiceImpl implements IPlatformRoleManageService {
//    @Resource
//    private IBaseMemberCacheService memberCacheService;
//
//    @Resource
//    private RoleRepository roleRepository;
//
//    @Resource
//    private IBaseAuthService baseAuthService;
//
//    @Resource
//    private IPlatformTemplateFeignService platformTemplateFeignService;
//
//
//    /**
//     * 根据名称，模糊、分页查询角色列表
//     *
//     * @param headers Http头部信息
//     * @param pageVO  接口参数
//     * @return 查询结果
//     */
//    @Override
//    public Wrapper<PageData<RoleManageVO>> pageRoles(HttpHeaders headers, PageRoleByNameVO pageVO) {
//        memberCacheService.needLoginFromManagePlatform(headers);
//        Specification<RoleDO> specification = (Specification<RoleDO>) (root, query, criteriaBuilder) -> {
//            List<Predicate> list = new ArrayList<>();
//            //去掉平台角色
//            list.add(criteriaBuilder.notEqual(root.get("relType").as(Integer.class), MemberRelationTypeEnum.PLATFORM.getCode()));
//            if(StringUtils.hasLength(pageVO.getRoleName())) {
//                list.add(criteriaBuilder.like(root.get("roleName").as(String.class), "%" + pageVO.getRoleName().trim() + "%"));
//            }
//
//            Predicate[] p = new Predicate[list.size()];
//            return criteriaBuilder.and(list.toArray(p));
//        };
//
//        Pageable page = PageRequest.of(pageVO.getCurrent() - 1, pageVO.getPageSize(), Sort.by("id").descending());
//        Page<RoleDO> pageList = roleRepository.findAll(specification, page);
//
//        return Wrapper.success(new PageData<>(pageList.getTotalElements(), pageList.getContent().stream().map(roleDO -> {
//            RoleManageVO roleManageVO = new RoleManageVO();
//            roleManageVO.setRoleId(roleDO.getId());
//            roleManageVO.setRoleName(roleDO.getRoleName());
//            roleManageVO.setBusinessTypeName(roleDO.getBusinessType().getBusinessTypeName());
//            roleManageVO.setMemberTypeName(MemberTypeEnum.getCodeMessage(roleDO.getMemberType().getTypeEnum()));
//            roleManageVO.setRoleTypeName(RoleTypeEnum.getName(roleDO.getRoleType().getTypeEnum()));
//            roleManageVO.setStatus(roleDO.getStatus());
//            return roleManageVO;
//        }).collect(Collectors.toList())));
//    }
//
//    /**
//     * 查询角色权限，以树形菜单形式返回
//     *
//     * @param headers Http头部信息
//     * @param idVO    接口参数
//     * @return 操作结果
//     */
//    @Override
//    public Wrapper<RoleAuthVO> treeRoleAuth(HttpHeaders headers, RoleIdVO idVO) {
//        memberCacheService.needLoginFromManagePlatform(headers);
//        RoleDO roleDO = roleRepository.findById(idVO.getRoleId()).orElse(null);
//        if(roleDO == null) {
//            return Wrapper.fail(ResponseCode.MC_MS_ROLE_DOES_NOT_EXIST);
//        }
//
//        RoleAuthVO authVO = new RoleAuthVO();
//        authVO.setRoleId(roleDO.getId());
//        authVO.setRoleName(roleDO.getRoleName());
//        authVO.setBusinessTypeName(roleDO.getBusinessType().getBusinessTypeName());
//        authVO.setMemberTypeName(MemberTypeEnum.getCodeMessage(roleDO.getMemberType().getTypeEnum()));
//        authVO.setRoleTypeName(RoleTypeEnum.getName(roleDO.getRoleType().getTypeEnum()));
//        authVO.setStatus(roleDO.getStatus());
//        authVO.setAuth(AuthBOUtils.transferToTree(roleDO.getRoleAuth().getConfigAuth()));
//        authVO.setCheckIds(roleDO.getRoleAuth().getAuth().stream().map(AuthBO::getId).collect(Collectors.toList()));
//        return Wrapper.success(authVO);
//    }
//
//    /**
//     * 查询左侧树形菜单勾选的Id列表
//     *
//     * @param headers Http头部信息
//     * @param idVO    接口参数
//     * @return 操作结果
//     */
//    @Override
//    public Wrapper<AuthTreeCheckIdsVO> getTreeMenuCheckIds(HttpHeaders headers, RoleIdVO idVO) {
//        memberCacheService.needLoginFromManagePlatform(headers);
//        RoleDO roleDO = roleRepository.findById(idVO.getRoleId()).orElse(null);
//        if(roleDO == null) {
//            return Wrapper.fail(ResponseCode.MC_MS_ROLE_DOES_NOT_EXIST);
//        }
//
//        AuthTreeCheckIdsVO checkIdsVO = new AuthTreeCheckIdsVO();
//        checkIdsVO.setCheckIds(roleDO.getRoleAuth().getAuth().stream().map(AuthBO::getId).collect(Collectors.toList()));
//
//        return Wrapper.success(checkIdsVO);
//    }
//
//    /**
//     * 根据左侧菜单Id，查询右侧按钮列表
//     *
//     * @param headers  Http头部信息
//     * @param getButtonVO 接口参数
//     * @return 操作结果
//     */
//    @Override
//    public Wrapper<RoleAuthButtonVO> getRoleAuthButtons(HttpHeaders headers, RoleGetButtonVO getButtonVO) {
//        memberCacheService.needLoginFromManagePlatform(headers);
//        RoleDO roleDO = roleRepository.findById(getButtonVO.getRoleId()).orElse(null);
//        if(roleDO == null) {
//            return Wrapper.fail(ResponseCode.MC_MS_ROLE_DOES_NOT_EXIST);
//        }
//
//        AuthBO configAuthBO = roleDO.getRoleAuth().getConfigAuth().stream().filter(auth -> auth.getId().equals(getButtonVO.getMenuId())).findFirst().orElse(null);
//        if(configAuthBO == null) {
//            return Wrapper.fail(ResponseCode.MC_MS_ROLE_AUTH_DOES_NOT_EXIST);
//        }
//
//        RoleAuthButtonVO buttonVO = new RoleAuthButtonVO();
//        buttonVO.setButtons(configAuthBO.getButtons().stream().map(button -> new AuthTreeButtonVO(button.getButtonId(), button.getTitle())).collect(Collectors.toList()));
//
//        AuthBO authBO = roleDO.getRoleAuth().getAuth().stream().filter(auth -> auth.getId().equals(getButtonVO.getMenuId())).findFirst().orElse(null);
//        if(authBO != null) {
//            buttonVO.setCheckIds(authBO.getButtons().stream().map(ButtonBO::getButtonId).collect(Collectors.toList()));
//        } else {
//            buttonVO.setCheckIds(new ArrayList<>());
//        }
//
//        return Wrapper.success(buttonVO);
//    }
//
//    /**
//     * 根据左侧菜单Id，查询右侧按钮列表勾选的Id列表
//     *
//     * @param headers  Http头部信息
//     * @param buttonVO 接口参数
//     * @return 操作结果
//     */
//    @Override
//    public Wrapper<AuthTreeCheckIdsVO> getTreeButtonCheckIds(HttpHeaders headers, RoleGetButtonVO buttonVO) {
//        memberCacheService.needLoginFromManagePlatform(headers);
//
//        RoleDO roleDO = roleRepository.findById(buttonVO.getRoleId()).orElse(null);
//        if(roleDO == null) {
//            return Wrapper.fail(ResponseCode.MC_MS_ROLE_DOES_NOT_EXIST);
//        }
//
//        AuthTreeCheckIdsVO checkIdsVO = new AuthTreeCheckIdsVO();
//        AuthBO authBO = roleDO.getRoleAuth().getAuth().stream().filter(auth -> auth.getId().equals(buttonVO.getMenuId())).findFirst().orElse(null);
//        if(authBO != null) {
//            checkIdsVO.setCheckIds(authBO.getButtons().stream().map(ButtonBO::getButtonId).collect(Collectors.toList()));
//        } else {
//            checkIdsVO.setCheckIds(new ArrayList<>());
//        }
//
//        return Wrapper.success(checkIdsVO);
//    }
//
//    /**
//     * 更新角色左侧菜单权限
//     *
//     * @param headers      Http头部信息
//     * @param updateMenuVO 接口参数
//     * @return 操作结果
//     */
//    @Override
//    public Wrapper<Void> updateRoleMenus(HttpHeaders headers, RoleUpdateMenuVO updateMenuVO) {
//        memberCacheService.needLoginFromManagePlatform(headers);
//        RoleDO roleDO = roleRepository.findById(updateMenuVO.getRoleId()).orElse(null);
//        if(roleDO == null) {
//            return Wrapper.fail(ResponseCode.MC_MS_ROLE_DOES_NOT_EXIST);
//        }
//
//        if (CollectionUtils.isEmpty(updateMenuVO.getMenuIds())) {
//            roleDO.getRoleAuth().setAuth(new ArrayList<>());
//        } else {
//            if(updateMenuVO.getMenuIds().stream().anyMatch(menuId -> roleDO.getRoleAuth().getConfigAuth().stream().noneMatch(authBO -> authBO.getId().equals(menuId)))) {
//                return Wrapper.fail(ResponseCode.MC_MS_ROLE_AUTH_DOES_NOT_EXIST);
//            }
//
//            //移除不存在的
//            roleDO.getRoleAuth().getAuth().removeIf(auth -> !updateMenuVO.getMenuIds().contains(auth.getId()));
//            //添加新增的
//            List<Long> addMenuIds = updateMenuVO.getMenuIds().stream().filter(id -> roleDO.getRoleAuth().getAuth().stream().noneMatch(authBO -> authBO.getId().equals(id))).collect(Collectors.toList());
//            List<AuthBO> authBOList = roleDO.getRoleAuth().getConfigAuth().stream().filter(m -> addMenuIds.contains(m.getId())).collect(Collectors.toList());
//            roleDO.getRoleAuth().getAuth().addAll(authBOList);
//        }
//
//        roleRepository.saveAndFlush(roleDO);
//
//        //更新平台会员关系、会员、会员角色、用户的权限
//        return baseAuthService.updateMemberAuthByUpdateRoleAuth(roleDO);
//    }
//
//    /**
//     * 更新角色左侧菜单关联的右侧按钮列表
//     *
//     * @param headers            Http头部信息
//     * @param updateMenuButtonVO 接口参数
//     * @return 操作结果
//     */
//    @Override
//    public Wrapper<Void> updateRoleMenuButtons(HttpHeaders headers, RoleUpdateMenuButtonVO updateMenuButtonVO) {
//        memberCacheService.needLoginFromManagePlatform(headers);
//        RoleDO roleDO = roleRepository.findById(updateMenuButtonVO.getRoleId()).orElse(null);
//        if(roleDO == null) {
//            return Wrapper.fail(ResponseCode.MC_MS_ROLE_DOES_NOT_EXIST);
//        }
//
//        AuthBO authBO = roleDO.getRoleAuth().getAuth().stream().filter(menu -> menu.getId().equals(updateMenuButtonVO.getMenuId())).findFirst().orElse(null);
//        if (authBO == null) {
//            return Wrapper.fail(ResponseCode.MC_MS_ROLE_AUTH_DOES_NOT_EXIST);
//        }
//
//        AuthBO configAuthBO = roleDO.getRoleAuth().getConfigAuth().stream().filter(menu -> menu.getId().equals(updateMenuButtonVO.getMenuId())).findFirst().orElse(null);
//        if (configAuthBO == null) {
//            return Wrapper.fail(ResponseCode.MC_MS_ROLE_AUTH_DOES_NOT_EXIST);
//        }
//
//        if(CollectionUtils.isEmpty(updateMenuButtonVO.getButtonIds())) {
//            authBO.getButtons().clear();
//        } else {
//            if(updateMenuButtonVO.getButtonIds().stream().anyMatch(buttonId -> configAuthBO.getButtons().stream().noneMatch(button -> button.getButtonId().equals(buttonId)))) {
//                return Wrapper.fail(ResponseCode.MC_MS_ROLE_AUTH_BUTTON_DOES_NOT_EXIST);
//            }
//
//            List<ButtonBO> buttons = configAuthBO.getButtons().stream().filter(button -> updateMenuButtonVO.getButtonIds().contains(button.getButtonId())).collect(Collectors.toList());
//            authBO.setButtons(buttons);
//        }
//
//        roleRepository.saveAndFlush(roleDO);
//
//        //更新平台会员关系、会员、会员角色、用户的权限
//        return baseAuthService.updateMemberAuthByUpdateRoleAuth(roleDO);
//    }
//
//    /**
//     * 修改角色状态
//     *
//     * @param headers  Http头部信息
//     * @param statusVO 接口参数
//     * @return 操作结果
//     */
//    @Override
//    public Wrapper<Void> updateRoleStatus(HttpHeaders headers, RoleUpdateStatusVO statusVO) {
//        memberCacheService.needLoginFromManagePlatform(headers);
//        RoleDO roleDO = roleRepository.findById(statusVO.getRoleId()).orElse(null);
//        if(roleDO == null) {
//            return Wrapper.fail(ResponseCode.MC_MS_ROLE_DOES_NOT_EXIST);
//        }
//
//        roleDO.setStatus(statusVO.getStatus());
//        roleRepository.saveAndFlush(roleDO);
//
//        //异步通知店铺模板服务
//        platformTemplateFeignService.notifyRoleStatusChangedAsync(roleDO.getId(), roleDO.getStatus());
//
//        return Wrapper.success();
//    }
//}
